package com.qmhl.toolposition.activity

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.hjq.toast.Toaster
import com.lxj.xpopup.XPopup
import com.qmhl.toolposition.R
import com.qmhl.toolposition.adapter.VipShowAdapter
import com.qmhl.toolposition.api.UserService
import com.qmhl.toolposition.api.content.GoodsResponse
import com.qmhl.toolposition.api.content.PayData
import com.qmhl.toolposition.base.BaseActivity
import com.qmhl.toolposition.databinding.ActivityVipBinding
import com.qmhl.toolposition.databinding.PopupVipPayBinding
import com.qmhl.toolposition.event.LoginEvent
import com.qmhl.toolposition.utils.PUtils
import com.qmhl.toolposition.utils.PreferenceUtil
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus


class VipActivity : BaseActivity() {

    private lateinit var binding: ActivityVipBinding

    lateinit var mIWXAPI: IWXAPI

    var goodsId: Long = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityVipBinding.inflate(layoutInflater)
        setContentView(binding.root)


    }

    override fun initData() {
        super.initData()
        setRecyclerView()
        //通过WXAPIFactory工厂，获取IWXAPI的实例
        mIWXAPI = WXAPIFactory.createWXAPI(this, "wx6bb40171e11f15da", true);

    }


    fun transferWxPay() {


        var dialog = XPopup.Builder(this)
            .asLoading("请稍后，正在为您创建支付")

        dialog.show()


        lifecycleScope.launch {
            var content = UserService.create()
                .ashzjPay(goodsId)
            if (content.code == 200) {
                dialog.dismiss()
                var payData = content.data
                goPay(payData)
            } else {
                Toaster.showShort(content.msg)
            }

        }


    }

    private fun goPay(payData: PayData) {
        var mPayReq = PayReq();
        //AppId
        mPayReq.appId = payData.appid;
        //微信支付分配的商户号
        mPayReq.partnerId = payData.partnerid;
        //微信返回的支付交易会话ID
        mPayReq.prepayId = payData.prepayid;
        //暂填写固定值Sign=WXPay
        mPayReq.packageValue = "Sign=WXPay";
        //随机字符串，不长于32位。推荐随机数生成算法
        mPayReq.nonceStr = payData.noncestr;
        //时间戳
        mPayReq.timeStamp = payData.timestamp;
        //签名
        mPayReq.sign = payData.sign;

        mIWXAPI.sendReq(mPayReq);
    }


    private fun setRecyclerView() {


        lifecycleScope.launch {
            var content = UserService.create()
                .getGoodList()
            if (content.code == 200) {

                setRv(content)

            }
        }


    }

    private fun setRv(content: GoodsResponse) {
        val data = content.data
        data[0].isSelect = true
        goodsId = data[0].id.toLong()

        val adapter = VipShowAdapter(content.data)

        val layoutManager = LinearLayoutManager(applicationContext)
        binding.rv.layoutManager = layoutManager
        binding.rv.adapter = adapter

        adapter.setOnItemClickListener { adapter, view, position ->
            data.forEach {
                it.isSelect = false
            }
            data[position].isSelect = true
            goodsId = data[position].id.toLong()
            adapter.submitList(data)
            adapter.notifyDataSetChanged()
        }
    }


    /**
     * 弹出设置 popupWindow
     * **/
    private fun showPopupWindow(position: Int) {
        val popupWindow = PopupWindow()

        val binding: PopupVipPayBinding = PopupVipPayBinding.inflate(layoutInflater)


        popupWindow.contentView = binding.root
        popupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT
        popupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow.isOutsideTouchable = true

        val mainActivity = LayoutInflater.from(this).inflate(R.layout.activity_vip, null)
        popupWindow.showAtLocation(mainActivity, Gravity.BOTTOM, 0, 0)

        var layoutParams = this.window?.attributes
        layoutParams?.alpha = 0.5f

        this.window?.attributes = layoutParams

        popupWindow.setOnDismissListener {
            val layoutParams1 = this.window?.attributes
            layoutParams1?.alpha = 1.0f;
            this.window?.attributes = layoutParams1


        }


        //取消popupWindow
        binding.btnPay.setOnClickListener {
            transferWxPay()
            //点击支付后取消弹窗
            popupWindow.dismiss()
        }

    }

    override fun initListener() {
        super.initListener()

        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.rbCheck.setOnCheckedChangeListener { view, isCheck ->

            binding.rbCheck.isChecked = isCheck

        }

        binding.btnOpen.setOnClickListener {
            canShowPopup()
        }

        binding.tvVip.setOnClickListener {
            val intent = Intent(this, AgreementActivity::class.java).apply {
                putExtra("url", PUtils.Config.payAgreement_assert)
                putExtra("title", PUtils.Config.payAgreement_title)
            }
            startActivity(intent)
        }

    }


    private fun canShowPopup() {
        var currentUser = PreferenceUtil.getCurrentUser()
        if (!currentUser.isLogin) {
            EventBus.getDefault().postSticky(LoginEvent(0))
        } else {
            showPopupWindow(0)
        }

    }

}